
#include <cstddef>
#include <iostream>
using namespace std;

struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
  };
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
    
   ListNode rootNode(0);
        ListNode *pCurNode = &rootNode;
        int forward = 0;
        while(l1||l2)
        {
            int v1 = (l1 ? l1->val : 0);
            int v2 = (l2 ? l2->val : 0);
            int sum = v1 + v2 + forward;
            forward = sum / 10;
            sum = sum % 10;
            ListNode *pNode = new ListNode(sum);
            pCurNode->next = pNode;
            pCurNode = pNode;
            if(l1) l1 = l1->next;
            if(l2) l2 = l2 ->next;
        }
        if(forward > 0)
        {
            ListNode *pNode = new ListNode(forward);
            pCurNode->next = pNode;
        }
        return rootNode.next;
        
    }

void TestaddTwoNumbers()
{
    ListNode* l1 = new ListNode(5);
    ListNode* l2 = new ListNode(6);
    
    l1->next=new ListNode(3);
    l1->next->next = new ListNode(1);
    l1->next->next->next = new ListNode(1);
    
    l2->next = new ListNode(4);
    l2->next->next = new ListNode(2);
    
    
    ListNode* resultNode = addTwoNumbers(l1,l2);
    while(resultNode)
    {
        cout<<resultNode->val<<' ';
        resultNode = resultNode->next;
    }
 
}
